package net.awpspace.mobile.management.book;

import java.util.Vector;

import javax.microedition.midlet.MIDlet;

import net.awpspace.mobile.form.BaseForm;
import net.awpspace.mobile.global.Client;
import net.awpspace.mobile.global.Global;

import com.sun.lwuit.Button;
import com.sun.lwuit.CheckBox;
import com.sun.lwuit.Command;
import com.sun.lwuit.Container;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;

/**
 * View list books
 * 
 * @author Diep
 */
public class ViewDelete extends BaseForm {

	private Vector books;
	private Vector boxes;

	private Command cmdSelectAll;
	private Command cmdSelectNone;
	private Command cmdDone;

	public ViewDelete(MIDlet app, BaseForm parent, Vector books) {
		super(app, parent);
		setTitle(Global.BOOK_DELETE);
		setLayout(new BorderLayout());

		this.books = books;
		boxes = new Vector();
		cmdSelectAll = new Command("Select All");
		cmdSelectNone = new Command("Select None");
		cmdDone = new Command("Done");

		Container container = new Container(new BoxLayout(BoxLayout.Y_AXIS));
		for (int i = 0; i < books.size(); ++i) {
			CheckBox cb = new CheckBox(
					((BookModel) books.elementAt(i)).getName());
			boxes.addElement(cb);
			container.addComponent(cb);
		}
		addComponent(BorderLayout.CENTER, container);

		addCommand(cmdSelectAll);
		addCommand(cmdSelectNone);
		addComponent(BorderLayout.SOUTH, new Button(cmdDone));
	}

	protected void processCommand(ActionEvent e) {
		if (e.getCommand().equals(cmdSelectAll)) {
			selectAll(true);
		} else if (e.getCommand().equals(cmdSelectNone)) {
			selectAll(false);
		} else if (e.getCommand().equals(cmdDone)) {
			for (int i = 0; i < boxes.size(); ++i) {
				if (((CheckBox) boxes.elementAt(i)).isSelected()) {
					Client.getInstance().delete(
							((BookModel) books.elementAt(i)).getId());
				}
			}
			showBack();
		}
	}

	private void selectAll(boolean select) {
		for (int i = 0; i < boxes.size(); ++i) {
			((CheckBox) boxes.elementAt(i)).setSelected(select);
		}
	}
}